<template>
    <div class="l-rblock l-form-viewer" style="padding:8px;">
        <el-form
            :model="formData"
            :rules="rules"
            size="mini"
            labelPosition="right"
            labelWidth="120px"
            ref="form"
            >
            <div class="l-auto-window ">
                <el-tabs v-model="activeName" type="card">
                    <el-tab-pane class="l-tabs-container" :label="$t('基础权限')" name="tab0">
                        <el-row :gutter="0">
                            <div class="l-rblock">
                                <el-col v-if="lr_formLookAuth('api_authmanage_f_IsTimeAuth')" :span="24" >
                                    <el-form-item 
                                        :label="$t('限制访问时间')" 
                                        prop="api_authmanage_f_IsTimeAuth"
                                        > 
                                        <el-switch  
                                            :disabled="!lr_formEditAuth('api_authmanage_f_IsTimeAuth',false || isReadOnly)" 
                                            :activeValue="0" 
                                            :inactiveValue="1" 
                                            v-model="formData.api_authmanage_f_IsTimeAuth" 
                                            active-text="是"
                                            inactive-text="否"
                                            active-color="rgba(144, 238, 144, 1)"
                                            inactive-color="#C0CCDA"
                                            />
                                    </el-form-item>
                                </el-col>
                                <el-col v-if="lr_formLookAuth('api_authmanage_f_BeginTime')&&formData.api_authmanage_f_IsTimeAuth==0" :span="12" >
                                    <el-form-item 
                                        :label="$t('开始时间')" 
                                        prop="api_authmanage_f_BeginTime"
                                        > 
                                        <l-time   :disabled="!lr_formEditAuth('api_authmanage_f_BeginTime',isReadOnly)" :readonly="false" format="HH:mm:ss" :clearable="true" v-model="formData.api_authmanage_f_BeginTime" :placeholder="$t('please select')" />
                                    </el-form-item>
                                </el-col>
                                <el-col v-if="lr_formLookAuth('api_authmanage_f_EndTime')&&formData.api_authmanage_f_IsTimeAuth==0" :span="12" >
                                    <el-form-item 
                                        :label="$t('结束时间')" 
                                        prop="api_authmanage_f_EndTime"
                                        > 
                                        <l-time   :disabled="!lr_formEditAuth('api_authmanage_f_EndTime',isReadOnly)" :readonly="false" format="HH:mm:ss" :clearable="true" v-model="formData.api_authmanage_f_EndTime" :placeholder="$t('please select')" />
                                    </el-form-item>
                                </el-col>
                                <el-col v-if="lr_formLookAuth('api_authmanage_f_IsIpAuth')" :span="24" >
                                    <el-form-item 
                                        :label="$t('限制IP访问')" 
                                        prop="api_authmanage_f_IsIpAuth"
                                        > 
                                        <el-switch  
                                            :disabled="!lr_formEditAuth('api_authmanage_f_IsIpAuth',false || isReadOnly)" 
                                            :activeValue="0" 
                                            :inactiveValue="1" 
                                            v-model="formData.api_authmanage_f_IsIpAuth" 
                                            active-text="是"
                                            inactive-text="否"
                                            active-color="rgba(255, 140, 0, 1)"
                                            inactive-color="#C0CCDA"
                                            />
                                    </el-form-item>
                                </el-col>
                                <el-col v-if="lr_formLookAuth('api_authmanage_f_IpAuthType')&&formData.api_authmanage_f_IsIpAuth==0" :span="24" >
                                    <el-form-item 
                                        :label="$t('IP 类型')" 
                                        prop="api_authmanage_f_IpAuthType"
                                        > 
                                        <el-radio-group v-model="formData.api_authmanage_f_IpAuthType"  size="mini" :disabled="!lr_formEditAuth('api_authmanage_f_IpAuthType',false || isReadOnly)" >
                                            <el-radio :label="1" border>黑名单</el-radio>
                                            <el-radio :label="0" border>白名单</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                </el-col>
                                <el-col v-if="lr_formLookAuth('api_authmanage_f_IpAuth')&&formData.api_authmanage_f_IsIpAuth==0" :span="24" >
                                    <el-form-item 
                                        :label="$t('配置IP')" 
                                        prop="api_authmanage_f_IpAuth"
                                        > 
                                        <el-input type="textarea"  :disabled="!lr_formEditAuth('api_authmanage_f_IpAuth',isReadOnly)" :rows="9" v-model="formData.api_authmanage_f_IpAuth" :placeholder="$t('多个ip地址请用‘，’隔开')" />
                                    </el-form-item>
                                </el-col>
                            </div>
                        </el-row>
                    </el-tab-pane>
                    <el-tab-pane class="l-tabs-container" :label="$t('用户权限')" name="tab1">
                        <el-row :gutter="0">
                            <div class="l-rblock" >
                                <l-edit-table
                                    addBtnText="添加用户"
                                    :dataSource="formUsers"
                                    @addRow="handleUserClick"
                                    @deleteRow="handleTableBtnClick"
                                    >
                                    <el-table-column
                                        v-slot="scope"
                                        label="姓名"
                                        minWidth="110">
                                        {{scope.row.name}}
                                    </el-table-column>
                                    <el-table-column
                                        v-slot="scope"
                                        label="公司"
                                        minWidth="150">
                                        {{getUserCompany(scope.row.companyid)}}
                                    </el-table-column>
                                    <el-table-column
                                        v-slot="scope"
                                        label="部门"
                                        minWidth="110">
                                        {{getUserDept(scope.row.deptid)}}
                                    </el-table-column>
                                </l-edit-table >
                            </div>
                        </el-row>
                    </el-tab-pane>
                    <el-tab-pane class="l-tabs-container" :label="$t('角色权限')" name="tab2">
                        <el-row :gutter="0">
                            <div class="l-rblock" >
                                <l-edit-table
                                    addBtnText="添加角色"
                                    :dataSource="formRoles"
                                    @addRow="handleAddRole"
                                    @deleteRow="handleDeleteRole"
                                    >
                                    <el-table-column
                                        v-slot="scope"
                                        label="编号"
                                        width="110">
                                        {{getRoleCode(scope.row.f_ObjectId)}}
                                    </el-table-column>
                                    <el-table-column
                                        v-slot="scope"
                                        prop="f_ObjectId"
                                        label="名称"
                                        minWidth="100">
                                         {{getRoleName(scope.row.f_ObjectId)}}
                                    </el-table-column>
                                </l-edit-table >
                            </div>
                        </el-row>
                    </el-tab-pane>

                </el-tabs>
            </div>
        </el-form>

        <!-- 添加角色 -->
        <l-dialog
            :title="$t('添加角色')"
            :visible.sync="selectRoleVisible"
            :height="480"
            width="800px"

            @ok="handleRoleSelectOk"
            @closed="handleRoleSelectClosed"
        >
            <l-role-select-panel ref="roleSelectPanel" ></l-role-select-panel>
        </l-dialog>
        <!-- 添加用户 -->
        <l-dialog
            :title="$t('添加用户')"
            :visible.sync="selectUserVisible"
            :height="480"
            width="1024px"
            @ok="handleUserSelectOk"
            @closed="handleUserSelectClosed"
            >
            <l-user-select-panel ref="userSelectPanel"></l-user-select-panel>
        </l-dialog>

    </div>
</template>
<script>
const api = window.$api.apimanage.apimaintain

export default {
    props: {
        isReadOnly: {
            type: Boolean,
            default: false
        },
        authFormEditRow:{
            f_Id:"",
        },
    },
    data(){
        return {
            moduleCode: 'apiManage_authmanage',
            activeName: 'tab0',
            formData: {
                api_authmanage_f_Id:"", // 唯一标识(GUID)
                api_authmanage_f_MaintainId:"",//接口信息管理外键【api_maintain】
                api_authmanage_f_IsTimeAuth:0, // 限制访问时间
                api_authmanage_f_BeginTime:"", // 开始时间
                api_authmanage_f_EndTime:"", // 结束时间
                api_authmanage_f_IsIpAuth:0, // 限制IP访问
                api_authmanage_f_IpAuthType:NaN, // IP 类型
                api_authmanage_f_IpAuth:"", // 配置IP
                api_authmanage_f_RoleAuth:"",//角色权限
                api_authmanage_f_UserAuth:""//用户权限

            },
            rules: {
                api_authmanage_f_IsTimeAuth:[
                    { required: true, message: 'please select限制访问时间' },
                ],
                api_authmanage_f_IsIpAuth:[
                    { required: true, message: 'please select限制IP访问' },
                ],

            },
            //角色信息
            formRoles:[],
            selectRoleVisible:false,

            //用户信息
            formUsers:[],
            selectUserVisible:false,
        };
    },
    computed: {
        
    },
    methods: {
        // Reset表单
        resetForm() {
            this.formRoles = []
            this.formUsers = []
            this.$formClear(this.$refs.form)
            this.activeName = 'tab0'
            
        },
        // 校验表单
        async validateForm() {
            if (!await this.$formValidateWraper(this.$refs.form)) {
                return false  
            }
            if(this.formData.api_authmanage_f_BeginTime>=this.formData.api_authmanage_f_EndTime){
                this.$message({
                    type: 'warning',
                    message: `开始时间需要小于结束时间！`
                })     
                return
            }
            
            return true
        },
        // 设置表单数据
        setForm(data) {
            this.$setFormData(this.formData,data,'api_authmanage')

        },
        // 获取表单数据
        getForm() {
            return this.$getFormData(this.formData,'api_authmanage')

        },

        async loadFormData({ maintainid}) {
            this.formData.api_authmanage_f_MaintainId=this.authFormEditRow.f_Id
            const data = await this.$awaitWraper(api.getauthmanage(maintainid))
            if (data) {
                this.getFormUsers(data.f_UserAuth)
                this.getFormRoles(data.f_RoleAuth)
                this.setForm(data)
                return true
            }
            else {
                return false
            }
        },

        async saveForm() {
            const postData = this.getForm()
            if(this.formData.api_authmanage_f_Id){//Edit
                return await this.$awaitWraper(api.updateauthmanage(this.formData.api_authmanage_f_Id, postData))
            }else{//Add
                return await this.$awaitWraper(api.addauthmanage(postData))
            }
        },
        //角色选择
        getRoleName(value){
            this.lr_loadRole(value)
            return (this.lr_role[value] || {}).f_FullName || ''
        },
        getRoleCode(value){
            this.lr_loadRole(value)
            return (this.lr_role[value] || {}).f_EnCode || ''
        },
        handleAddRole(){
            this.selectRoleVisible = true
        },
        handleRoleSelectClosed(){
            this.$refs.roleSelectPanel.resetForm()
        },
        async handleRoleSelectOk(){
            let select = await this.$refs.roleSelectPanel.getForm();
            const selectData = select.map(t=>{return {f_Category:1,f_ObjectId:t.f_RoleId} })
            const addData = selectData.filter(t=>this.formRoles.findIndex(t2=>t2.f_ObjectId == t.f_ObjectId) == -1 )
            this.formRoles.push(...addData)
            this.formData.api_authmanage_f_RoleAuth=String(this.formRoles.map(t=>t.f_ObjectId))
            this.selectRoleVisible = false
        },
        handleDeleteRole(data){
            this.formRoles.splice(data.index,1)
        },
        getFormRoles(RoleAuth){
            if(RoleAuth){
                const RoleAuthList=RoleAuth.split(',');
                RoleAuthList.forEach(item => {
                    const role = this.lr_role[item]
                    if(role){
                        this.formRoles.push({f_Category:1,f_ObjectId:role.f_RoleId})
                    }
                })
            }
        },
        //用户选择
        handleUserClick() {
            this.selectUserVisible = true;
        },
        async handleUserSelectOk() {
            let select = await this.$refs.userSelectPanel.getForm();
            let selectData = select.map((t) => {
                return {id: t.f_UserId, name: t.f_RealName,companyid:t.f_CompanyId,deptid:t.f_DepartmentId};
            });
            this.addTableData(selectData);
            this.formData.api_authmanage_f_UserAuth=String(this.formUsers.map(t=>t.id))
            this.selectUserVisible = false;
        },
        handleUserSelectClosed() {
            this.$refs.userSelectPanel.resetForm();
        },
        handleTableBtnClick({ index }) {
            this.formUsers.splice(index, 1);
        },
        addTableData(selectData) {
            let addData = selectData.filter(
            (t) =>
                this.formUsers.findIndex((t2) => t2.id == t.id) == -1
            );
            this.formUsers = this.formUsers.concat(addData);
        },
        getUserCompany(value){
            this.lr_loadCompanyName(value)
            return (this.lr_companyList.find(t=>t.f_CompanyId == value) || {}).f_FullName || ''
        },
        getUserDept(value){
            this.lr_loadDepartment(value)
            return (this.lr_department[value] || {}).f_FullName || ''
        },
        getFormUsers(UserAuths){
            if(UserAuths){
                const UserAuthList=UserAuths.split(',');
                UserAuthList.forEach(item => {
                    const user = this.lr_users[item]
                    if(user){
                        this.formUsers.push({id: user.f_UserId, name: user.f_RealName,companyid:user.f_CompanyId,deptid:user.f_DepartmentId})
                    }
                })
            }
        }
    }
}
</script>